package com.ruoyi.common.utils;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.PictureData;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFPicture;
import org.apache.poi.xssf.usermodel.XSSFShape;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;

public class XlslUtil {
    //获取工作铺
    public static Workbook getWorkBook(MultipartFile file) {
        // 获得文件名
        String fileName = file.getOriginalFilename();
        // 创建Workbook工作薄对象，表示整个excel
        Workbook workbook = null;
        try {
            // 获取excel文件的io流
            InputStream is = file.getInputStream();
            // 根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
            if (fileName.endsWith("xls")) {
                // 2003
                return new HSSFWorkbook(is);
            } else if (fileName.endsWith("xlsx")) {
                // 2007
                return new XSSFWorkbook(is);
            }
        } catch (IOException e) {
            System.err.println(e.getMessage());
        }
        return workbook;
    }

    //获取xlsl 图片
    public static Map<String, PictureData> getSheetPictures(XSSFSheet sheet) {
        Map<String, PictureData> sheetPictures = new HashMap<>();

        if (ObjectUtils.isEmpty(sheet.getDrawingPatriarch())){
            return sheetPictures;
        }
        // 获取浮动图片
        for (XSSFShape shape : sheet.getDrawingPatriarch().getShapes()) {
            if (shape instanceof XSSFPicture) {
                XSSFPicture picture = (XSSFPicture) shape;
                ClientAnchor anchor = picture.getClientAnchor();

                // 计算单元格引用
                int row1 = anchor.getRow1();
                int col1 = anchor.getCol1();
                String cellReference = row1 + ":" + col1; // 假设每个图片只覆盖一个单元格

                PictureData pictureData = picture.getPictureData();
                sheetPictures.put(cellReference, pictureData);
            }
        }
        return sheetPictures;
    }

    // 压缩并编码二进制数据
    public static String compressAndEncode(byte[] data) throws IOException {
        return Base64.getEncoder().encodeToString(data);
    }

    // 解码并解压缩
    public static byte[] decodeAndDecompress(String encodedData) throws IOException {
        // 解码
        byte[] compressedData = Base64.getDecoder().decode(encodedData);

        // 解压缩
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(compressedData);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try (GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream)) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = gzipInputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
        }
        return byteArrayOutputStream.toByteArray();
    }

    //判断是否数字
    public static boolean isNumericUsingRegex(String str) {
        if (str == null || str.isEmpty()) {
            return false;
        }
        // 正则表达式匹配整数或浮点数，包括正负号和科学计数法
        return str.matches("-?\\d+(\\.\\d+)?([eE][-+]?\\d+)?");
    }

    //矫正 xlsl 日期格式
    public static String dateFmt(long daysToAdd){
        // 基准日期（1900年1月1日）
        LocalDate baseDate = LocalDate.of(1900, 1, 1);

        // 给定的天数
        // 计算目标日期
        LocalDate targetDate = baseDate.plusDays(daysToAdd - 2); // 减1是因为从1900-01-01开始计数

        // 输出结果
        return  targetDate.toString();
    }
}
